package com.jacobson.huobi.utils

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import java.io.File

object ApkUtil {
    fun installApk(
        context: Context,
        auth: String?,
        apkPath: String?
    ) {
        val intent = Intent(Intent.ACTION_VIEW)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val apkUri = FileProvider.getUriForFile(
                context,
                auth!!,
                File(apkPath)
            )
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(
                Uri.fromFile(File(apkPath)),
                "application/vnd.android.package-archive"
            )
        }
        context.startActivity(intent)
    }

    fun getVersionCode(context: Context): Int {
        val pm = context.packageManager
        return try {
            val pi =
                pm.getPackageInfo(context.packageName, PackageManager.GET_ACTIVITIES)
            pi.versionCode
        } catch (e: Exception) {
            e.printStackTrace()
            0
        } catch (e: NoSuchMethodError) {
            e.printStackTrace()
            0
        }
    }
}